package com.bosch.in.rtp1.ept.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.bosch.in.rtp1.ept.action.LoginAction;

/**
 * This class is used to manage access control on every configuration pages.
 * In order to edit configuration information, user has to provide valid password in advance.
 * @author TPR1HC
 *
 */
public class AuthenticationFilter implements Filter {
	
	/*
	 * redirect URL to login form, parameter should keep track original link user want to access
	 * Parameter name must be the same with LoginForm attribute.
	 */
	private final String onErrorUrl = "/auth.do?originalUrl=";
	 
	public void destroy() {}
	
	/*
	 * (non-Javadoc)
	 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
	    HttpServletResponse res = (HttpServletResponse) response;
	    HttpSession session = req.getSession();
	    
	    if (session.getAttribute(LoginAction.LOGON) != null) {
	    	// refresh time life
	    	session.setAttribute(LoginAction.LOGON, session.getAttribute(LoginAction.LOGON));
	    	chain.doFilter(request, response);
	    }
	    else {
	    	res.sendRedirect(req.getContextPath() + onErrorUrl + getUri(req));
	    }
	}
	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub
		
	}
	
	/**
	 * keep track original URL which one user want to access
	 * @param req	Http request parameter
	 * @return
	 */
	private String getUri(HttpServletRequest req) {
	    String reqUrl = req.getRequestURI().toString();
	    reqUrl = reqUrl.replace(req.getContextPath(), "");
	    String queryString = req.getQueryString();
	    if (queryString != null) {
	        reqUrl += "?"+queryString;
	    }
	    return reqUrl;
	}
}
	

